import { RoleHelper } from "./base.role";

export class Transporter implements IRole {
    role: RoleType = 'transporter';
    bodyPart: BodyPartConstant[] = [CARRY, CARRY, MOVE, MOVE];
    priority: number = 2;
    minCost: number = 300;

    work(creep: Creep) {
        this.stateSwitch(creep);

        if (creep.memory.working) {
            // 送能
            this.transportEnergy(creep);
        } else {
            let isGet = false;
            // 1. 获取存储的能源
            isGet = RoleHelper.getStoreEnergy(creep);
            // 2. 拾取地上的能源
            if (!isGet) {
                RoleHelper.pickupEnergy(creep);
            }
        }
    }
    stateSwitch(creep: Creep) {
        if (creep.memory.working === undefined) {
            creep.memory.working = false;
        }

        if (creep.store.getFreeCapacity() == 0) {
            // 背包满了，切换至送能模式
            creep.memory.working = true;

        } else if (creep.store.getUsedCapacity() == 0) {
            // 背包空了，切换至取能模式
            creep.memory.working = false;
        }
    }

    // 送能
    transportEnergy(creep: Creep): boolean {
        const energyConsumer = this.findEnergyConsumer(creep);

        if (energyConsumer) {
            this.transferEnergy(creep, energyConsumer);
            return true;
        }

        return false;
    }

    // 找到能源消费者
    private findEnergyConsumer(creep: Creep) {
        // 1. 优先找建筑
        const structureConsumer = creep.pos.findClosestByPath(FIND_STRUCTURES, {
            filter: s => RoleHelper.canReceiveEnergy(s) &&
                s.store.getFreeCapacity(RESOURCE_ENERGY) > 0
        });
        if (structureConsumer) return structureConsumer;

        // 2.其次找 creep
        const creepConsumer = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: c => c !== creep && c.store.getFreeCapacity(RESOURCE_ENERGY) > 0
        });
        if (creepConsumer) return creepConsumer;

        return null;
    }

    // 送能
    private transferEnergy(creep: Creep, target: Structure | Creep): boolean {
        const result = creep.transfer(target, RESOURCE_ENERGY);
        if (result === ERR_NOT_IN_RANGE) {
            RoleHelper.moveToTarget(creep, target, '#aaffaa');
            creep.say('📦送能');
            return true;
        } else if (result === OK) {
            creep.say('✅送达');
            return true;
        }

        return false;
    }
}